package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
        //组成集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
        //从集合中获取对应的播放时长，userId和trackId;
        Query query=Query.query(Criteria.where("trackId").is(trackId));
        UserListenProcess userListenProcess=mongoTemplate.findOne(query, UserListenProcess.class,collectionName);
        //判断
        if(null!=userListenProcess){
            return userListenProcess.getBreakSecond();
        }
        return new BigDecimal("0.00");
    }

    @Override
    public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
        //先查询MongoDB中是否有该声音的播放记录；
        //组成集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
        //从集合中获取对应的播放时长，userId和trackId;
        Query query=Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
        UserListenProcess userListenProcess=mongoTemplate.findOne(query, UserListenProcess.class,collectionName);
        //判断
        if(null!=userListenProcess){
            //覆盖播放记录
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setUpdateTime(new Date());
        } else {
            //新增播放记录
            userListenProcess = new UserListenProcess();
            //赋值
            userListenProcess.setUserId(userId);
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
        }
        //保存数据
        this.mongoTemplate.save(userListenProcess,collectionName);
        //利用分布式锁思想防止恶意刷单,选择Hash结构
        //key=userId:trackId; value="1",24H
        String key = userId+":"+userListenProcessVo.getTrackId();
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, "1", 24, TimeUnit.HOURS);
        //判断是否有锁
        if(result){
            //说明当前这个用户是第一次播放，专辑+声音，播放量+1；
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setCount(1);
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            trackStatMqVo.setBusinessNo(uuid);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSON(trackStatMqVo));

        }
    }

    @Override
    public Map<String, Object> getLatelyTrack(Long userId) {
        //	创建map 集合
        Map<String, Object> map = new HashMap<>();
        //获取集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
        //设置查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"updateTime")).limit(1);
        UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //判断
        if(null!=userListenProcess){
            map.put("trackId",userListenProcess.getTrackId());
            map.put("albumId",userListenProcess.getAlbumId());
        }
        //返回数据
        return map;
    }
}
